/**
 * customer和km elasticsearch相关的接口
 */

import {Service} from 'egg';
import * as elasticsearch from 'elasticsearch';
import * as _ from 'lodash';

const es: any = {
  customerIndex: 'customer',
  _client: '',
  client(app: any) {
    const esUrl = app.appConfig.esUrl;
    if (!this._client) {
      this._client =  new elasticsearch.Client({
        host: esUrl,
        log: 'warning',
      });
    }
    return this._client;
  },
};

export default class EsService extends Service {
  public async batchAddIndex2Cust(data: any[]): Promise<any> {
    const result: any = {success: false};
    const { ctx, app } = this;
    data = _.cloneDeep(data);
    try {
      const actions: any[] = [];
      data.forEach((doc) => {
        const action = {
          index: {
            _index: es.customerIndex,
            _type: es.customerIndex,
            _routing: doc.account,
            _id: doc._id,
          },
        };
        delete doc._id;
        if (!doc.notifyTime) {
          delete doc.notifyTime;
        }
        actions.push(action, doc);
      });
      const rep = await es.client(app).bulk({body: actions});
      result.data = rep;
      result.success = true;
      return result;
    } catch (error) {
      ctx.logger.error('batchAddIndex2Cust error', error);
      return result;
    }
  }

  public async queryName(name: string, account: string, id: string) {
    const { ctx, app } = this;
    const result: any = { success: false };
    try {
      const maxNum = 10000;
      let query;
      query = {
        bool: {
          should: [{
            match_phrase: {name},
          }],
          filter: [{
            term: {account},
          }],
          minimum_should_match: 1,
        },
      };
      const searchData = {
        index: es.customerIndex,
        type: es.customerIndex,
        size: maxNum,
        body: {query},
        routing: account,
        _source: ['_id'],
      };
      const resp = await es.client(app).search(searchData);
      // ctx.logger.info('===========name======+++++ss+++++++ ' + JSON.stringify(searchData));
      // ctx.logger.info('===========name======++++++++++++ ' + JSON.stringify(resp));
      const docs = resp.hits.hits;
      const ids: any[] = [];
      if (docs.length > 0) {
        docs.forEach((doc) => {
          ids.push(doc._id);
        });
      }
      if (resp.total > maxNum) {
        ctx.logger.info('--verify-----queryName--需要观察----' + account);
        result.success = true;
      } else {
        if (_.indexOf(ids, id) > -1) {
          result.success = true;
        }
      }
      return result;
    } catch (error) {
      ctx.logger.error('queryName error', error);
      return result;
    }
  }

  public async queryPhone(phone: any, account: string, id: string) {
    const { ctx, app } = this;
    const result: any = { success: false };
    if (!(phone && phone[0])) {
      return result;
    }
    try {
      const maxNum = 10000;
      const query = {
        bool: {
          should: [{
            term: {phone: phone[0]},
          }],
          filter: [{
            term: {account},
          }],
          minimum_should_match: 1,
        },
      };
      const searchData = {
        index: es.customerIndex,
        type: es.customerIndex,
        size: maxNum,
        body: {query},
        routing: account,
        _source: ['_id'],
      };
      const resp = await es.client(app).search(searchData);
      // ctx.logger.info('==========phone=======++++++sss++++++ ' + JSON.stringify(searchData));
      // ctx.logger.info('==========phone=======++++++++++++ ' + JSON.stringify(resp));
      const docs = resp.hits.hits;
      const ids: any[] = [];
      if (docs.length > 0) {
        docs.forEach((doc) => {
          ids.push(doc._id);
        });
      }
      if (resp.total > maxNum) {
        result.success = true;
      } else {
        if (_.indexOf(ids, id) > -1) {
          result.success = true;
        }
      }
      return result;
    } catch (error) {
      ctx.logger.error('queryPhone error', error);
      return result;
    }
  }
}
